/*
 * @file        CCAM_Frame.cpp
 * @version     1.0
 * @author      Johance
 * @email:421465201@qq.com
 * @date        2013-04-24
 * @brief       CCAM_Frame 
 */
#include "CocosPCH.h"

#include "CCAM_Frame.h"
#include "MatrixTransformer.h"

CCAM_Frame *CCAM_Frame::create()
{
	CCAM_Frame *pRet = new CCAM_Frame();
	if(pRet == NULL)
	{
		return NULL;
	}

	pRet->autorelease();

	return pRet;
}

CCAM_Frame::CCAM_Frame()
{
}

CCAM_Frame::~CCAM_Frame(void)
{	
	for(unsigned int i = 0; i < m_vecFrameElement.size(); i++)
	{
		delete m_vecFrameElement[i];
	}

	m_vecFrameElement.clear();
}

CCAM_Frame::FrameElement* CCAM_Frame::AddElement(short TextureID, unsigned int Opacity, AffineTransform trans)
{
	FrameElement *pElement = new FrameElement();

	pElement->TextureID = TextureID;
	pElement->Opacity = Opacity;
	pElement->trans = trans;

	m_vecFrameElement.push_back(pElement);
	return pElement;
}

void CCAM_Frame::AddSound(std::string strSoundName)
{
	m_strSoundName = strSoundName;
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8
	if(m_strSoundName.size() > 0)
	{
		m_strSoundName.replace(m_strSoundName.size()-3, 3, "wav");
	}
#endif
}

void CCAM_Frame::Update(Node *pAnimNode)
{
	if(m_strSoundName.size() > 0)
	{
		//SimpleAudioEngine::getInstance()->playEffect((std::string("sound/")+m_strSoundName).c_str(), false);
		//CCLOG(m_strSoundName.c_str());
	}

    for (auto child : pAnimNode->getChildren())
    {
        child->setVisible(false);
    }

    Point pos;
    Point scale;
    Point skew;
	for(unsigned int i = 0; i < m_vecFrameElement.size(); i++)
	{
		Sprite *pSprite = (Sprite*)pAnimNode->getChildByTag(m_vecFrameElement[i]->TextureID);
        MatrixTransformer::getGetTSK(m_vecFrameElement[i]->trans, pos, scale, skew);
        pSprite->setPosition(pos);
        pSprite->setScale(scale.x, scale.y);
        pSprite->setRotationSkewX(skew.x);
        pSprite->setRotationSkewY(-skew.y);
        pSprite->setOpacity(m_vecFrameElement[i]->Opacity);

		pSprite->setVisible(true);
		pAnimNode->reorderChild(pSprite, i);
	}
}

void CCAM_Frame::SetPosScale(float fScale)
{
	for(unsigned int i = 0; i < m_vecFrameElement.size(); i++)
	{
		AffineTransform &addTrans = m_vecFrameElement[i]->trans;
		addTrans.tx *= fScale;
		addTrans.ty *= fScale;
	}
}